package com.artezio.vacation.dao.ldap;

import com.artezio.vacation.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import java.util.List;

/**
 *
 * Implementation of the user ldap dao
 */
@Repository
public class UserLdapDAOImpl implements UserLdapDAO {

    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * Find user in active directory with given login
     *
     * @param login
     * @return user
     */
    @Override
    public User findUser(String login) {
        return (User) ldapTemplate.lookup(login, new UserAttributesMapper());
    }

    /**
     * Find all users in active directory
     * List include all users from active directory
     *
     * @return list
     */
    public List getAllUsers() {
        return ldapTemplate.search("", "(objectclass=users)", new UserAttributesMapper());
    }

//    public static void main(String[] args) {
//        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("test.xml");
//        LdapTemplate ldapTemplate1 = (LdapTemplate) applicationContext.getBean("ldapTemplate");
//        List list = ldapTemplate1.list("CN=Users,DC=ARTGROUP,DC=local");
//        for (Object object : list) {
//            System.out.println(object.toString());
//        }
//    }
}

/**
 * Mapper for the results received from active directory
 *
 */
 class UserAttributesMapper implements AttributesMapper {
    public Object mapFromAttributes(Attributes attributes) throws NamingException {
        User user = new User();
        user.setName((String) attributes.get("givenName").get());
        user.setSurname((String) attributes.get("sn").get());
        user.setLogin((String) attributes.get("sAMAccountName").get());
        user.setEmail((String) attributes.get("mail").get() );
        return user;
    }
}
